package br.cin.stadium.application.activities;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import br.cin.stadium.application.R;
import br.cin.stadium.application.util.ButtonServer;
import br.cin.stadium.application.util.Logger;
import br.cin.stadium.middleware.StadiumException;
import br.cin.stadium.middleware.StadiumTS;
import br.cin.stadium.middleware.event.EventRemote;
import br.cin.stadium.middleware.event.EventRemoteListener;
import br.cin.stadium.middleware.media.Media;
import br.cin.stadium.middleware.media.MediaReference;


public class StadiumActivity extends Activity 
{
	private StadiumActivity m_sa = this;

	private static final int MENU_REFRESH = 0;
	private static final int MENU_ADD = 1;
	private static final int MENU_FIND = 2;
	private static final int MAKE_VIDEO = 3;
	private static final int ADD_VIDEO_TEST = 4;
	
	private static final int LEFT_CORNER_SECTOR = 1;
	private static final int RIGHT_CORNER_SECTOR = 2;
	
	private static final int DIALOG_FIND = 0;
	
	private AlertDialog alertDialogFind = null;
	
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stadiumactivity);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		menu.add(0, MENU_REFRESH, 0, "Refresh").setIcon(R.drawable.menu_refresh);;
	    menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.menu_add);
	    menu.add(0, MENU_FIND, 0, "Find").setIcon(R.drawable.menu_search);
	    menu.add(0, MAKE_VIDEO, 0, "Make a video").setIcon(R.drawable.video_icon);
	    menu.add(0, ADD_VIDEO_TEST, 0, "ADD TEST").setIcon(R.drawable.menu_add);
	    
	    return true;
	}
	
	private int contadorSector = 1;
	private int nameInt = 1;

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    switch (item.getItemId()) 
	    {
		    case MENU_REFRESH:
		    	refreshServer();
		        return true;
			case MENU_ADD:
				callAddActivity(VideoGridList.class);
		        return true;
			case MENU_FIND:
				showDialog(DIALOG_FIND);
		        return true;
			case MAKE_VIDEO:
				this.StartVideoRecordActivity();
				break;
			case ADD_VIDEO_TEST:
				String name = "Zico_2";
				String type = "3gp";
				int stadiumSector = 1;
				InputStream a = this.getResources().openRawResource(R.raw.zico_1982);
		        byte[] buffer = null;
		        try {
		            buffer = new byte[a.available()];
		            a.read(buffer);
		        } catch (IOException e) { 
		            //empty
		        }    

				Media media = new Media(name, type, stadiumSector, buffer); // name, type, stadiumSector, content

				// publish the media
				try {
					StadiumTS.getInstance().write(media);
				} catch (StadiumException e) {
					Logger.logError("StadiumActivity", "onOptionsItemSelected", "WRITE MEDIA TEST NOTIFY", e);
					e.printStackTrace();
				}
				
				break;
	    }
	    
	    return false;
	}
	
	private void StartVideoRecordActivity()
	{
		Intent filho = new Intent(m_sa, VideoRecord.class);
		startActivity(filho);
	}
	
	private void refreshServer() 
	{
		
		Logger.log("StadiumActivity", "refreshServer", "Begin");

		try {
			StadiumTS.getInstance().unRegisterUnit();
			ArrayList<MediaReference> mediaRefs = StadiumTS.getInstance().readAll();
			
			System.out.println("JORGE - MEDIA REFS.size = " + mediaRefs.size());
			
			for (int i = 0; i < mediaRefs.size(); i++) {
				System.out.println("NAME = " + mediaRefs.get(i).getMediaName());
				System.out.println("SECTOR = " + mediaRefs.get(i).getSector());
				
			}
			
			RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
			refreshLayout(layout, mediaRefs);
			
		} catch (Exception e) {
			// TODO: handle exception
		}

		Logger.log("StadiumActivity", "refreshServer", "End");
	}
	
	private void refreshLayout(RelativeLayout layout, ArrayList<MediaReference> listServers) 
	{
		Logger.log("StadiumActivity", "refreshLayout", "Begin(" + listServers.size() + ")");

		MediaReference mediaRef;
		Log.i("MAINPROJECT", "Criando os botoes");
		layout.removeAllViews();
		
		int topLeft = 0;
		int topRight = 0;
		
		if (listServers != null)
		{
			for (int i = 0; i < listServers.size(); i++) 
			{
				mediaRef = listServers.get(i);
				Log.i("MAINPROJECT", 
					  "Adicinonando MEDIA " + mediaRef.getMediaName() + " Sector=" + mediaRef.getSector());
				
				LayoutParams lp = new LayoutParams(mediaRef.getMediaName().length() * 9 + 12, 40);
				
				ButtonServer buttonView = new ButtonServer(m_sa);
				buttonView.setText(mediaRef.getMediaName());
				buttonView.setHint(mediaRef.getMediaName());
				buttonView.setMediaRef(mediaRef);
				
				if (mediaRef.getSector() == LEFT_CORNER_SECTOR)
				{
					lp.leftMargin = 10;
					topLeft += 40;
					lp.topMargin = topLeft;
				}
				else if (mediaRef.getSector() == RIGHT_CORNER_SECTOR)
				{
					lp.leftMargin = 400;
					topRight += 40;
					lp.topMargin = topRight;				
				}
				else
				{
					//bug...
				}

				buttonView.setOnClickListener(new OnClickListener() 
				{
					public void onClick(View v) 
					{
						ButtonServer b = (ButtonServer) v;
						Intent filho = new Intent(m_sa, VideoPlayer.class);
						filho.putExtra("mediaName", b.getMediaRef().getMediaName());
						filho.putExtra("mediaIp", b.getMediaRef().getServerLocation().getIp());
						filho.putExtra("mediaPort", b.getMediaRef().getServerLocation().getPort());
						filho.putExtra("mediaSector", b.getMediaRef().getSector());
						startActivity(filho);
					}
				});

				layout.addView(buttonView, lp);
			}			
		}		

		Logger.log("StadiumActivity", "refreshLayout", "End");
	}
	
	
	private void callAddActivity(Class classe) 
	{
		Logger.log("StadiumActivity", "callAddActivity", "Begin(" + classe.getName() + ")");

		Intent filho = new Intent(m_sa, classe);
		startActivity(filho);
		Logger.log("StadiumActivity", "callAddActivity", "End");
	}

	
	@Override
    protected Dialog onCreateDialog(int id) {
		Logger.log("StadiumActivity", "onCreateDialog", "Begin(" + id + ")");

		switch (id) {
        	case DIALOG_FIND:
        		// This example shows how to add a custom layout to an AlertDialog
                LayoutInflater factory = LayoutInflater.from(this);
                final View textEntryView = factory.inflate(R.layout.alert_dialog_find, null);
                alertDialogFind = new AlertDialog.Builder(StadiumActivity.this)
                    .setIcon(R.drawable.alert_dialog_icon)
                    .setTitle(R.string.alert_dialog_find_title)
                    .setView(textEntryView)
                    .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                        
                    	public void onClick(DialogInterface dialog, int whichButton) {
                        	String name = ((EditText) alertDialogFind.findViewById(R.id.find_name)).getText().toString();
                        	String sector = ((EditText) alertDialogFind.findViewById(R.id.find_sector)).getText().toString();
                        	
                        	ArrayList<MediaReference> mediaRefs = null; 
                        	if (!name.equals(""))
                        	{
                        		
                        		try {
									mediaRefs = StadiumTS.getInstance().read(name);
								} catch (StadiumException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}                        		
                        	}
                        	else if (!sector.equals(""))
                        	{
                        		try {
									mediaRefs = StadiumTS.getInstance().read(Integer.parseInt(sector));
								} catch (NumberFormatException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (StadiumException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
                        	}
                        	RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
                        	refreshLayout(layout, mediaRefs);
                        }
                    })
                    .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //empty
                        }
                    })
                    .create();
                
                return alertDialogFind;
        }

		Logger.log("StadiumActivity", "onCreateDialog", "End");
        return null;
	}
	

}
